<template>
  <div>
    <el-container>
      <el-header :style="obj">
        <div>
          <img src alt />
          <router-link :to="'/home'" style="color:rgb(202, 214, 157)">
            <span id="header-title">COCO视频</span>
          </router-link>
        </div>
        <el-input placeholder="用户名称" clearable v-model="queryInfo.query.keyWord" @clear="search()">
          <el-button id="btn1" slot="append" icon="el-icon-search" @click="search()"></el-button>
        </el-input>
        <div>
          <i class="el-icon-upload" @click="showUpload()" style="cursor:pointer"></i>
          <el-dropdown style="color:rgb(202, 214, 157)">
            <span>
              <i class="el-icon-stopwatch" style="cursor:pointer"></i>
            </span>
            <el-dropdown-menu slot="dropdown" style="width:300px;height:350px;">
              <el-scrollbar style="height: 100%;">
                <el-dropdown-item divided v-for="o in historyList" :key="o.id" width="100px">
                  <router-link :to="'/video/' + o.videoId">
                    <el-row>
                      <el-col :span="8">
                        <span>{{o.videoName}}</span>
                      </el-col>
                      <el-col :span="16">
                        <span>{{o.hisTime}}</span>
                      </el-col>
                    </el-row>
                  </router-link>
                </el-dropdown-item>
                <el-dropdown-item
                  style="float:right"
                  :style="{'display': (historyList.length<=0 ? 'none':'block')}"
                >
                  <el-button type="danger" round @click="deleteHistory()" size="small">删除记录</el-button>
                </el-dropdown-item>
              </el-scrollbar>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown style="color:rgb(202, 214, 157)">
            <span>
              <i class="el-icon-user" style="cursor:pointer"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item divided @click.native="showInfo()">用户信息</el-dropdown-item>
              <el-dropdown-item divided @click.native="showCollection()">收藏列表</el-dropdown-item>
              <el-dropdown-item divided @click.native="logout()">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <!-- 上传弹窗 -->
      <add-or-update v-if="showUpVisible" ref="addOrUpdate"></add-or-update>
      <el-main>
        <div id="allBody">
          <!-- 视频和评论区域 -->
          <div id="video-talk">
            <!-- 视频区域 -->
            <div>
              <video-player
                class="video-player vjs-custom-skin"
                ref="videoPlayer"
                :playsinline="true"
                :options="playerOptions"
              ></video-player>
              <div style="display: flex;align-items: center;">
                <h3>{{videoModel.videoName}}</h3>
                <p>&nbsp;&nbsp;{{videoModel.remark}}</p>
              </div>
              <!-- 点赞及一些其他功能 -->
              <div style="display: flex;justify-content: space-between;">
                <span>{{videoModel.sum}}次观看·{{videoModel.createTime}}</span>
                <div>
                  <span>
                    点赞
                    <i :class="point" @click="zan()" style="cursor:pointer" />
                  </span>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <!-- 评论区域 -->
            <div>
              <h2>欢迎讨论视频</h2>
              <el-card class="box-card" style="margin-bottom: 100px;">
                <div v-for="o in commentsList" :key="o.id" class="text item">
                  <span>{{o.comments}}</span>
                  <el-divider content-position="right">{{o.userName}}--{{o.createTime}}</el-divider>
                </div>
                <div id="pinglun">
                  <el-input placeholder="评论" clearable v-model="commentsModel.comments"></el-input>
                  <el-button type="primary" plain @click="commentsInto()">提交</el-button>
                </div>
              </el-card>
            </div>
          </div>
          <!-- 其他推荐视频 -->
          <el-card style="padding:0px">
            <div>
              <img src="../assets/广告.png" width="330px" />
            </div>
            <el-divider></el-divider>
            <p>猜你喜欢的视频</p>
            <div v-for="o in videoInfoList" :key="o.id">
              <router-link :to="'/video/' + o.id">
                <div id="video-like">
                  <img :src="o.imageId" width="130px" height="100px" />
                  <div>
                    <span id="sss">{{o.remark}}</span>
                    <p>{{o.sum}}次观看·</p>
                  </div>
                </div>
              </router-link>
            </div>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="queryInfo.pageIndex"
              :page-size="queryInfo.pageSize"
              layout="total, prev, pager, next"
              :total="total"
            >></el-pagination>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import AddOrUpdate from "./Dialog";
import Conversion from "../assets/js/conversion";
export default {
  components: {
    AddOrUpdate
  },
  data() {
    return {
      id: "",
      path: "",
      point: "el-icon-star-off",
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src:
              "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm" //url地址
          }
        ],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true //全屏按钮
        }
      },
      obj: {
        position: "static"
      },
      collection: {
        status: 0,
        videoId: ""
      },
      videoModel: {},
      videoInfoList: [],
      queryInfo: {
        query: {
          keyWord: "",
          typeId: [],
          times: []
        },
        pageIndex: 1,
        pageSize: 4
      },
      total: 0,
      showUpVisible: false,
      //历史记录
      historyList: [],
      commentsList: [],
      commentsModel: {
        videoId: "",
        comments: ""
      },
      //双向通信的数据
      path: "ws://api.coco.com/api/websocket",
      socket: ""
    };
  },
  watch: {
    $route() {
      this.id = this.$route.params.videoId; //获取传来的参数
      this.updateWatch(); //路由变化时就重新执行这个方法 更新传来的参数
      this.getVideoTv();
      this.getHistoryList();
    }
  },
  mounted() {
    window.addEventListener("scroll", this.showIcon);
    var that = this;
    Conversion.$on("V_refresh", function() {
      that.getVideoForYou();
    });
  },
  created() {
    this.id = this.$route.params.videoId;
    this.updateWatch();
    this.getHistoryList();
    this.getVideoTv();
    this.commentsGet();
    this.init();
  },
  methods: {
    //双向通信
    init: function() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function() {
      console.log("socket连接成功");
    },
    error: function() {
      console.log("连接错误");
    },
    getMessage: function(msg) {
      console.log(msg.data)
      this.open3(msg.data)
    },
    send: function() {
      this.socket.send(params);
    },
    close: function() {
      console.log("socket已经关闭");
    },
    //通知
    open3(msg) {
        this.$notify.info({
          title: '消息',
          message: '大片'+ msg + '已经上上架！'
        });
      },
    //累加浏览次数
    async updateWatch() {
      await this.$http
        .put("/manager/video/updateWatch/" + this.id)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //获取历史记录
    async getHistoryList() {
      await this.$http
        .get("/portal/common/getTodeyHistory")
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          this.historyList = resp.data;
          console.log(this.historyList);
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //删除历史记录
    async deleteHistory() {
      await this.$http
        .delete("/portal/common/deleteHistory")
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          this.getHistoryList();
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //退出
    async logout() {
      this.setLoadStatus("logOut");
      window.sessionStorage.clear();
      this.$router.push("/login");
    },
    //设置登录状态
    async setLoadStatus(userId) {
      await this.$http
        .put(`manager/user/updateStatus/${userId}/${"0"}`)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("更新失败！");
        });
    },
    //通过id获取视频数据
    async getVideoTv() {
      await this.$http
        .get("/portal/facade/getVideoById/" + this.id)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          console.log(resp.data);
          this.videoModel = resp.data;
          this.playerOptions.sources[0].src = this.videoModel.videoUrl;
          this.queryInfo.query.typeId[0] = this.videoModel.typeId;
          this.getVideoForYou();
          this.getCollectionStatus();
          this.saveRecord();
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //保存用户历史记录
    async saveRecord() {
      await this.$http
        .post("/portal/common/saveHistory", this.collection)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //搜索
    search() {
      var jsonString = JSON.stringify(this.queryInfo.query);
      this.$router.push({
        path: "/search",
        query: { keyWord: jsonString }
      });
    },
    //获取视频收藏状态
    async getCollectionStatus() {
      this.collection.videoId = this.id;
      await this.$http
        .get("/portal/video/isCollection/" + this.id)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          this.collection.status = resp.data;
          if (this.collection.status == 1) {
            this.point = "el-icon-star-on";
          } else {
            this.point = "el-icon-star-off";
          }
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //获取推荐视频
    async getVideoForYou() {
      await this.$http
        .post("/portal/facade/getVideoByCondition", this.queryInfo)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          this.videoInfoList = resp.data.data;
          console.log(resp.data);
          this.total = resp.data.total;
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pageSize = newSize;
      this.getVideoForYou();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pageIndex = newPage;
      this.getVideoForYou();
    },
    showIcon() {
      if (
        !!document.documentElement.scrollTop &&
        document.documentElement.scrollTop > 500
      ) {
        this.obj.position = "fixed";
      } else {
        this.obj.position = "static";
      }
    },
    async zan() {
      if (this.collection.status == 1) {
        this.point = "el-icon-star-off";
        this.collection.status = 0;
      } else {
        this.point = "el-icon-star-on";
        this.collection.status = 1;
      }

      await this.$http
        .post("/portal/video/changCollectionStatus", this.collection)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //获取评论
    async commentsGet() {
      await this.$http
        .get("/manager/comments/selectComments/" + this.id)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          console.log(resp.data);
          this.commentsList = resp.data;
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    //添加评论
    async commentsInto() {
      this.commentsModel.videoId = this.id;
      await this.$http
        .post("/manager/comments/save", this.commentsModel)
        .then(resp => {
          if (resp.status !== 200) return this.$message.error("获取数据失败！");
          this.commentsModel.comments = "";
          this.commentsGet();
        })
        .catch(() => {
          this.$message.error("获取异常！");
        });
    },
    showUpload() {
      this.showUpVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init();
      });
    },
    showInfo() {
      this.showUpVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.initInfo();
      });
    },
    showCollection() {
      this.showUpVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.initCollection();
      });
    }
  }
};
</script>

<style lang="less" scoped>
.home-container {
  height: 100%;
}
.el-header {
  background-color: #232325;
  display: flex;
  width: 100%;
  position: static;
  z-index: 999;
  justify-content: space-between;
  padding-left: 3%;
  padding-right: 3%;
  align-items: center;
  color: rgb(202, 214, 157);
  font-style: italic;
  font-size: 25px;
  font-family: "微软雅黑";
  > div {
    i {
      margin-left: 30px;
      font-size: 30px;
    }
  }
  > .el-input {
    width: 30%;
  }
}

#pinglun {
  display: flex;
  justify-content: space-between;
}

.el-main {
  background-color: rgb(249, 249, 249);
  padding: 0;
  margin: 0;
  > #allBody {
    width: 86%;
    margin: auto;
    margin-top: 25px;
    justify-content: space-between;
    display: flex;
    > #video-talk {
      width: 70%;
    }
    > .el-card {
      width: 28%;
    }
  }
}

#video-like {
  display: flex;
  margin: 5px 0;
  > div {
    margin: 0 15px;
    > p {
      font-size: 12px;
    }
    > #sss {
      font-family: "微软雅黑", "黑体", "宋体";
      font-weight: bold;
      font-size: 13px;
    }
  }
}

.el-card .el-card__body {
  padding: 0 !important;
}
</style>